from framework.base_page import BasePage
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time
from framework.public_class import con
from framework.public_class import logger


class ComicDetailPage(BasePage):
    """漫画详情页相关操作"""

    # 查找顶部漫画标题
    def find_comic_name(self, detail_comic_name_xpath):
        """查找顶部漫画标题"""
        comic_name_el = self.find_element(selector=detail_comic_name_xpath)
        return comic_name_el

    # 刷新漫画详情页
    def refresh_comic_detail_window(self):
        """刷新漫画详情页"""
        self.refresh(log_msg="刷新漫画详情页")

    # 点击收藏或者已收藏按钮
    def click_collect_btn(self):
        """点击收藏或者已收藏按钮"""
        # 查找 收藏 按钮是否被隐藏，如果被隐藏则现在显示的状态为 已收藏
        collect_btn_el = self.find_element(
            selector="xpath=>//span[@class='btn btn-collect collect' and @style='display: none;']",
            isshow_error=1)
        if collect_btn_el:  # 隐藏的收藏按钮被找到
            # 下一步查找 已收藏 按钮
            click_el = self.find_element(
                selector="xpath=>//span[@class='btn btn-collect collected']",
                isshow_error=1)
            self.element_click(element=click_el, log_msg="点击已收藏按钮")
        else:  # 隐藏的收藏按钮未被找到，说明现在是 未收藏状态
            # 下一步查找 收藏 按钮
            click_el = self.find_element(
                selector="xpath=>//span[@class='btn btn-collect collect']",
                isshow_error=1)
            self.element_click(element=click_el, log_msg="点击收藏按钮")

    # 点击收藏弹窗上的“我的收藏”元素
    def click_my_collect_btn(self):
        """点击收藏弹窗上的“我的收藏”元素"""
        self.element_click(selector="xpath=>//li[@data-bookid='addcollect']")

    # 等待“已添加至 我的收藏!”toast显示出来
    def wait_add_to_my_collect_is_visible(self, toast_text, timeout):
        """等待“已添加至 我的收藏!”toast显示出来"""
        # locator = (By.XPATH, "//div[@class='layer-custom-text' and text()=%s]" % toast_text)
        locator = (By.XPATH, "//div[@class='layer-custom-text']")
        return self.toast_is_visible(locator=locator, text=toast_text, timeout=timeout)

    # 等待点击收藏或已收藏按钮后的收藏弹窗弹出
    def wait_collect_div_is_visible(self, timeout):
        """等待点击收藏或已收藏按钮后的收藏弹窗弹出"""
        locator = (By.XPATH, "//*[@class='layui-layer layui-layer-page add-to-book common-header-cat-container']")
        return self.is_visible(locator=locator, timeout=timeout)

    # 点击创建书单
    def click_create_book(self):
        """点击创建书单"""
        self.element_click(selector="xpath=>//li[@class='book-item J_layerBookItem create-book-warp']")

    # 输入书单名, 点击确定
    def input_book_title(self, title):
        """输入书单名,点击确定"""
        self.input_text(selector="xpath=>//textarea[@class='input J_bookTitle']", text=title)
        self.element_click(selector="xpath=>//div[@class='confirm J_confirm']")

    # 等待添加书单成功的toast显示出来
    def wait_creatbook_success_toast_is_visible(self, toast_text, timeout):
        """等待添加书单成功的toast显示出来"""
        # locator = (By.XPATH, "//div[@class='layer-custom-text' and text()='已添加至 %s']" % toast_text)
        locator = (By.XPATH, "//div[@class='layer-custom-text']")
        toast_text = "已添加至 %s" % toast_text
        return self.toast_is_visible(locator=locator, text=toast_text, timeout=timeout)


class DacallPage(BasePage):
    """打call相关操作"""

    # 鼠标移动到给作者加油dacall处
    def mouse_moveto_dacall(self):
        dacall_el = self.find_element(selector="class=>btn-func")
        self.move_to_element(dacall_el, location="foot")  # 浏览器向下滑动到dacall处
        # 执行移动操作
        try:
            ActionChains(self.driver).move_to_element(dacall_el).perform()  # 鼠标悬停在打call上
        except Exception as e:
            logger.error("鼠标悬停在打call上失败: %s" % e)
            self.get_windows_img(error_info="鼠标悬停打call")  # take screenshot

    # 等待赞赏、礼物、月票、推荐票、评分、分享 弹窗弹出
    def wait_dacall_div_is_visible(self):
        return self.is_visible(locator=(By.XPATH, "//div[@class='layui-layer layui-layer-page']"))

    # 点击赞赏、礼物、月票、推荐票、评分、分享
    def click_dacall_item(self, item_num):
        """1-赞赏、2-礼物、3-月票、4-推荐票、5-评分、6-分享"""
        if item_num == 1:
            self.element_click(selector="xpath=>//li[@class='item event-appreate']")
        elif item_num == 2:
            self.element_click(selector="xpath=>//li[@class='item event-present']")
        elif item_num == 3:
            self.element_click(selector="xpath=>//li[@class='item event-ticket']")
        elif item_num == 4:
            self.element_click(selector="xpath=>//li[@class='item event-feather']")
        elif item_num == 5:
            self.element_click(selector="xpath=>//li[@class='item event-mark']")
        elif item_num == 6:
            self.element_click(selector="xpath=>//li[@class='item event-share']")
        else:
            raise Exception("item_num must be in 1-6, please check item_num")

    # 点击 赞赏、礼物、月票、推荐票四个弹窗的立即赞赏/立即赠送/立即投票/立即投票四个按钮
    def click_zanshang_sub_btn(self):
        btn = self.find_element(selector="xpath=>//span[@class='btn-sub']")
        if btn.text == "立即赞赏":
            self.element_click(element=btn, log_msg="立即赞赏")
            return True
        elif btn.text == "去充值":
            self.get_windows_img(error_info="赞赏-账户钻石不足")
            return False
        else:
            self.get_windows_img(error_info="赞赏未知错误，请手动测试")
            return False

    # # 点击 礼物、月票、推荐票3个弹窗的立即赠送/立即投票/立即投票3个按钮
    def click_sub_btn(self, item: int):
        btn = self.find_element(selector="xpath=>//span[@class='btn-sub']")
        if item == 1:
            self.element_click(element=btn, log_msg="立即赠送")
        if item == 2 or item == 3:
            self.element_click(element=btn, log_msg="立即投票")

    # 赞赏、送礼物、月票、推荐票、评分等操作失败后，点击弹窗右上角的关闭按钮
    def click_close_btn(self):
        self.element_click(selector="xpath=>//i[@class='icon-close close']")

    # 等待赞赏、送礼物、月票、推荐票、评分"成功的toast显示
    def wait_dacall_success_toast_is_visible(self, item_num):
        """item_mun, 1--赞赏 2--送礼物, 3--月票 4--推荐票 5--评分"""
        zanshang_toast = "感谢主人的赞赏~本次共花费"
        liwu_toast = "主人，已经收到您送的礼物啦~"
        yuepiao_toast = "收下主人赠送的月票啦~"
        tuijianpiao_toast = "收下主人赠送的推荐票啦"
        pingfen_toast = "Thanks~评分成功"
        if item_num == 1:
            toast_is_visible = self.toast_is_visible(
                locator=(By.XPATH, "//div[@class='layer-custom-text layer-line']"), text=zanshang_toast)
        elif item_num == 2:
            toast_is_visible = self.toast_is_visible(
                locator=(By.XPATH, "//div[@class='layer-custom-text layer-line']"), text=liwu_toast)
        elif item_num == 3:
            toast_is_visible = self.toast_is_visible(
                locator=(By.XPATH, "//div[@class='layer-custom-text']"), text=yuepiao_toast)
        elif item_num == 4:
            toast_is_visible = self.toast_is_visible(
                locator=(By.XPATH, "//div[@class='layer-custom-text']"), text=tuijianpiao_toast)
        elif item_num == 5:
            toast_is_visible = self.toast_is_visible(
                locator=(By.XPATH, "//div[@class='layer-custom-text']"), text=pingfen_toast)
        else:
            raise Exception("item_num must be in 1-5, please check!")
        if toast_is_visible:
            return True
        else:
            self.click_close_btn()
            return False

    # 点击评分弹窗中的第五颗星
    def click_5_star(self):
        time.sleep(3)
        star_els = self.find_elements(selector="xpath=>//icon[@class='star']")
        self.mouse_stop_on_elment(element=star_els[-1])  # 鼠标悬停在最后一颗星上
        star_els_mouse_stop = self.find_elements(selector="xpath=>//div[@class='mark-star star-row']/icon")
        self.element_click(element=star_els_mouse_stop[-1], log_msg="五星")  # 点最高的那颗星，即五星
        # self.element_click(selector="xpath=>//div[@class='mark-star star-row']")

    # 点分享弹窗中的微信
    def click_weixin(self):
        self.element_click(selector="class=>acgn-share-ift-wechat")

    # 找二维码的div
    def qrcode_is_visible(self):
        return self.is_visible(locator=(By.XPATH, "//div[@class='acgn-share-qrcode js_share_qrcode']"))

    # 点击关闭微信二维码弹窗
    def weixin_popup_close(self):
        self.element_click(selector="xpath=>//div[@class='acgn-share-close js_share_qrcode_close']")


class CommentPage(BasePage):
    """评论相关模块"""
    uid = con.get_config(section="test_config", key="uid")
    main_comment_text = "哈哈哈，好好看"

    # 输入评论文字
    def input_comment_text(self, num=1):
        """
        回复别人的评论的时候输入框会有多个，num控制在第几个输入框输入评论的文字，1--代表主评论的输入框，2--回复评论的输入框
        """
        if num == 1:
            pinglun_el = self.find_element(selector="xpath=>//div[@class='model-head']")  # 定位输入框上面的漫评文字
            self.move_to_element(el=pinglun_el, location="top")  # 移动屏幕到漫评在顶部
            self.input_text(selector="class=>comment-textarea", text=self.main_comment_text)
        else:
            comment_textarea_els = self.find_elements(selector="class=>comment-textarea")
            self.move_to_element(el=comment_textarea_els[num-1], location="foot")
            self.input_text(element=comment_textarea_els[num-1], text=self.main_comment_text)

    # 点击吐槽一下
    def click_tucao(self, num: int=1, isfoot: int=0):
        """
        回复别人的评论的时候，吐槽一下就会多一个，需通过num选择点哪个吐槽一下
        :param num:  第几个吐槽一下按钮
        :param isfoot:  是否将吐槽一下按钮置于底部
        :return:
        """
        tucao_els = self.find_elements(selector="xpath=>//button[@class='comment-submit js_submit_comment']")
        if isfoot != 0:
            self.move_to_element(el=tucao_els[num-1], location="foot", keys_down=isfoot)  # 将吐槽一下按钮置于底部
            time.sleep(0.5)
        self.element_click(element=tucao_els[num-1], log_msg="点击第%d个‘吐槽一下’" % num)

    #  等待发表的评论是否显示出来
    def check_comment_success(self):
        return self.is_visible(locator=(By.XPATH, "//div[@class='comment-issue']"),
                               text=self.main_comment_text)  # 等评论显示出来

    # 找第一条非自己发表的未点赞的评论进行点赞
    # 20190310记录，pc端评论显示规则：先显示点赞数最高的前10条，然后按照时间倒序排序20条
    # 所以测试时只测试第一页即可，如果第一页都点过赞了，则报错，手动去点赞测试一次即可
    def prise(self):
        """返回找到的可点赞按钮的element"""
        # 先找未点赞的所有元素
        prise_els = self.find_elements(
            selector="xpath=>//i[@class='comment-ift-support js_comment_support' and @data-issupport='0']")
        prise_el = None
        for i in range(0, len(prise_els)):
            if prise_els[i].get_attribute("data-uid") != self.uid:
                # 找到不是自己发表的且未点赞的评论
                prise_el = prise_els[i]
                break
        if prise_el:  # 如果找到了
            self.move_to_element(el=prise_el, location="foot")  # 找到评论后向下滚动到可点赞按钮处
            time.sleep(1)
            self.element_click(element=prise_el, log_msg="click 点赞 按钮")
        else:  # 如果没找到
            logger.error("第一页评论未找到不是自己发表的且未点赞的评论，需手动测试！")
        return prise_el

    # 等待点赞成功的toast
    def wait_prise_success_toast(self):
        return self.toast_is_visible(locator=(By.XPATH, "//div[@class='comment-layer-modal']"), text="点赞成功!")

    # 找第一条非自己发表的评论并点击
    def click_reply_comment(self):
        reply_els = self.find_elements(selector="xpath=>//span[@class='comment-replay js_comment_replay']")  # 找所有的回复按钮
        # reply_els.reverse()
        reply_el = None
        for i in range(len(reply_els)):
            if reply_els[i].get_attribute("data-uid") != self.uid:
                reply_el = reply_els[i]
                self.move_to_element(el=reply_el, location="foot")  # 将回复按钮置于底部
                self.element_click(element=reply_el, log_msg="回复btn")
                break
        return reply_el
